package com.hzit.servlet;

import cn.hutool.core.util.StrUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * 类名：
 * 作者：WF
 * 功能：
 */
@WebServlet("/user")
public class UserServlet extends HttpServlet {

	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		//1. 得到请求参数
		String cmd = req.getParameter("cmd");
		if(StrUtil.isNotBlank(cmd)){
			if("login".equals(cmd)){
				login(req,resp);
			}
		}
	}
	//2. 用户登录处理逻辑  /user?cmd=login
	private void login(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		//2.1 得到用户名及密码
		String username = req.getParameter("username");
		String password = req.getParameter("password");
		//2.2 假设数据库的用户名为admin，密码为123
		if(!"admin".equals(username) || !"123".equals(password)){
			//2.2.1 输入错误后，重新跳转回登录页面
			req.setAttribute("msg","用户名或密码错误！");
			req.getRequestDispatcher("/login.jsp").forward(req,resp);   // 转发
		}else{
			//1. 保存用户信息到session中
			HttpSession session = req.getSession();
			session.setAttribute("username",username);
			//2. 成功后，可以跳转到学生列表
			resp.sendRedirect("/student?cmd=list");
		}
	}
}
